/*
 等待抢单界面，确定拼车时间页面需要调整
 支付页面待完成，目前仅支持微信支付
 */
var c = 0; //计时
var t;
$(document).ready(function () {
    var userId = $.cookie("userId");
    var socket = io.connect("http://" + $("#server").text() + ":8080");
    var orderId = null;

    var map_instance = null;
    var input_instance = null;

    socket.on('orderEnsure', function (driver) {
        console.log(driver); //todo 给顾客展示司机信息
    });

    $('#goback').click(function () {
        window.location.href = '/';
    });
    var scrollOption = {
        preset: 'datetime',
        minDate: new Date(),
        maxDate: new Date(2020, 12, 30, 59, 59),
        stepMinute: 5,
        theme: 'default',
        mode: 'mixed',
        display: 'bottom',
        lang: 'zh'
    };

    $('#pieceBusiness').click(function () {
        //the data need to be saved
        var entercarTime = $('#entercar_time').val();
        var entercarPeople = $('#entercar_people').val();
        var startPos = $('#start_pos').val();
        var endPos = $('#end_pos').val();
        var validate_startpos = window.utils.validate(startPos, "require");
        var validate_endpos = window.utils.validate(endPos, "require");
        var validate_entercarTime = window.utils.validate(entercarTime, "require");
        var validate_entercarPeople = window.utils.validate(entercarPeople, "require");

        var postData = {};
        postData.order_type = "PIECE";
        postData.total_time =  $('#daysSelect option:selected').text() +"-"+$('#daysSelect option:selected').val();
        postData.start_time = entercarTime;
        postData.total_count = entercarPeople;
        postData.start_addr = {};
        postData.end_addr = {};
        postData.start_addr.name = startPos;
        postData.start_addr.geo_point = $("#start_pos").attr('geo');
        postData.end_addr.name = endPos;
        postData.end_addr.geo_point = $("#end_pos").attr('geo');
        postData.distance = window.totalDistance;
        postData.price = $("#total_fee").text();

        socket.emit("customOnline", {id: userId});

        if (validate_startpos == true && validate_endpos == true && validate_entercarPeople == true && validate_entercarTime == true) {
            $.post('/piece/waitOrder',
                {order: JSON.stringify(postData)},
                function (data) {
                    if (data.redirect) {
                        window.utils.toast('waring', "您还未登录或登录过期");
                        setTimeout(function () {
                            window.location = data.redirect;
                        }, 2000);
                    } else {
                        orderId = data.id;
                        timedCount();
                        window.utils.toast('success', "生成订单成功, 等待司机抢单");
                    }
                });
        } else {
            window.utils.toast('warning', '未填写必填项');
            return;
        }
    });

    $(".geo-location").each(function () {
        $(this).click(function () {
            map_instance = window.utils.bdMap();
            input_instance = this;
            $("#geoInput").focus();
        });
    });

    $(".geo-sure").each(function () {
        $(this).click(function () {
            map_instance && map_instance.closeMap();
            $(input_instance).val(window.unique_marker.m_addr_info);
            $(input_instance).attr("geo", window.unique_marker.point.lng + "," + window.unique_marker.point.lat);
            $(input_instance).change();
        });
    });

    $(".geo-cancel").each(function () {
        $(this).click(function () {
            map_instance && map_instance.closeMap();
        });
    });

    $('#cancle-timer').click(function () {
        stopTimeCount();
        if (orderId) {
            $.post('/order/cancel', {id: orderId}, function (data) {
                console.log(data);
                if (data == 'success') {
                    window.utils.toast('success', "成功取消订单");
                    setTimeout(function () {
                        window.location.href = '/piece';
                    }, 2000);
                }
            });
        } else {
            window.utils.toast('error', "当前没有订单");
        }
    });

    $('.form-datetime').each(function () {
        $(this).scroller(scrollOption);
    });

    window.sureFee = function(){
        if(!!$("#start_pos").val() && !!$("#end_pos").val()) {
            if(parseInt($("#entercar_people").val()) > 0) {
                window.utils.mapSearch($("#start_pos").attr('geo'),
                    $("#end_pos").attr('geo'),map_instance,function(result){
                        var days = $('#daysSelect option:selected').val();
                        window.totalDistance = result.distance;
                        var totalcost = getTotalCosts(result.distance) * days * parseInt($("#entercar_people").val());
                        $("#total_fee").text(totalcost.toFixed(2));
                })

            } else {
                $("#entercar_people").val("1");
                window.utils.toast("error","输入人数有误");
            }
        }
    }
});


var stopTimeCount = function () {
    c = 0;
    setTimeout("document.getElementById('timer').innerText = 0", 0);
    clearTimeout(t);
};

var timedCount = function () {
    document.getElementById('timer-container').style.display = "block";
    document.getElementById('timer').innerText = c;
    c = c + 1;
    t = setTimeout('timedCount()', 1000);
};


var getPieceTime = function () {
    window.utils.toast('success', "请选择乘车时间");
    document.getElementById("piece-time").style.display = "block";
};

/*
 费用计算方式:
 起步价5元，免费3公里，之后每公里一元，没有等待时间
 (distance - 3) * 1 + 5
 */
var getTotalCosts = function (distance) {
    return distance < 3 ? 3 : ( distance + 2);
}